package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.IdeaComment;
import entity.User;
import util.DBHelp;
import util.RowMapper;

public class IdeaCommentDao {

	private DBHelp<IdeaComment> db=new DBHelp<IdeaComment>();
	
	public void save(IdeaComment ic){
		String sql="insert into t_ideacomment (id,content,createtime,user_id,idea_id) values(?,?,?,?,?)";
		db.executeSQL(sql, ic.getId(),ic.getContent(),ic.getCreatetime(),ic.getUser_id(),ic.getIdea_id());
	}
	public List<IdeaComment> find(String id){
		String sql="SELECT t_ideacomment.id,content,createtime,user_id,idea_id,username FROM t_ideacomment LEFT JOIN t_user ON t_ideacomment.user_id=t_user.id where idea_id=?";
		return db.executeQueryToList(sql, new RowMapper<IdeaComment>(){
	
		public IdeaComment mapRow(ResultSet rs) throws SQLException{
			IdeaComment ic=new IdeaComment();
			ic.setContent(rs.getString("content"));
			ic.setCreatetime(rs.getString("createtime"));
			ic.setId(rs.getString("id"));
			ic.setIdea_id(rs.getString("idea_id"));
			ic.setUser_id(rs.getString("user_id"));
		
			User user=new User();
			user.setId(rs.getString("user_id"));
			user.setUsername(rs.getString("username"));
			ic.setUser(user);
			return ic;
			}
		},id );
	}
	public IdeaComment findById(String id) {
		String sql="SELECT id,content,createtime,user_id,idea_id FROM t_ideacomment where id=?";
		return db.executeQueryToObject(sql, new IdeaCommentRowMapper(), id);
		
	}
	public void update(IdeaComment ic){
		String sql="update t_ideacomment set content=? where id=?";
		db.executeSQL(sql, ic.getContent(),ic.getId());
	}
	public class IdeaCommentRowMapper implements RowMapper<IdeaComment>{

		public IdeaComment mapRow(ResultSet rs) throws SQLException {
			IdeaComment ic=new IdeaComment();
			ic.setContent(rs.getString("content"));
			ic.setCreatetime(rs.getString("createtime"));
			ic.setId(rs.getString("id"));
			ic.setIdea_id(rs.getString("idea_id"));
			ic.setUser_id(rs.getString("user_id"));
		
			
			return ic;
			}
		}
	public void del(String id) {
		String sql="delete from t_ideacomment where id=?";
		db.executeSQL(sql, id);
	}
	public List<IdeaComment> findByIdeaId(String id) {
		String sql="select id,content,createtime,user_id,idea_id from t_ideacomment where idea_id=?";
		return db.executeQueryToList(sql, new IdeaCommentRowMapper(), id);
	}
		
	
}
